package wens.pig.dhm.formplugin.patrolscheme;

import kd.bos.base.BaseShowParameter;
import kd.bos.bill.OperationStatus;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.datamodel.ListSelectedRow;
import kd.bos.entity.datamodel.ListSelectedRowCollection;
import kd.bos.form.*;
import kd.bos.form.control.events.BeforeItemClickEvent;
import kd.bos.form.control.events.ItemClickEvent;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.events.MessageBoxClosedEvent;
import kd.bos.form.events.SetFilterEvent;
import kd.bos.form.field.events.BeforeFilterF7SelectEvent;
import kd.bos.form.operate.FormOperate;
import kd.bos.list.ListShowParameter;
import kd.bos.list.plugin.AbstractListPlugin;
import kd.bos.mvc.list.ListView;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import org.apache.commons.lang3.StringUtils;
import wens.pig.base.common.consts.BaseDataConst;
import wens.pig.base.common.consts.dhm.SchemePatrolPigFaConstant;
import wens.pig.base.common.enums.BillStatusEnum;
import wens.pig.base.common.enums.EnableEnum;
import wens.pig.base.utils.ObjectUtil;
import wens.pig.base.utils.PigGeryUtil;

import java.util.EventObject;

import static wens.pig.base.common.consts.BaseDataConst.F_ID;

public class SchemePatrolPigFaListPlugin extends AbstractListPlugin {
    /**
     * Type:boolean,Name:更新方案 列表按钮
     **/
    private final static String WENS_COPY_SCHEME = "wens_copy_scheme";
    private static final String ORG_FIELD = "orgField";
    private static final String VERSIONNUM = "V1.0";
    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        this.addItemClickListeners(WENS_COPY_SCHEME);
    }


    @Override
    public void afterCreateNewData(EventObject e) {
        ListView listView = (ListView) this.getView();
        MainEntityType dataType = EntityMetadataCache.getDataEntityType(listView.getBillFormId());
        this.getPageCache().put(ORG_FIELD, dataType.getMainOrg());
    }

    @Override
    public void filterColumnSetFilter(SetFilterEvent args) {
        ListShowParameter parameter = (ListShowParameter) this.getView().getFormShowParameter();
        if (parameter.isLookUp()) {
            return;
        }
        // 猪场字段
        String pigGeryFieldName = this.getPageCache().get(ORG_FIELD);
        // 猪场过滤
        if (args.getFieldName().startsWith(pigGeryFieldName)) {
            args.addCustomQFilter(new QFilter(F_ID, QCP.in, PigGeryUtil.getPermPigGeryOrgList()));
        }
    }

    @Override
    public void beforeItemClick(BeforeItemClickEvent evt) {
        super.beforeItemClick(evt);
        String key = evt.getItemKey();
        if (WENS_COPY_SCHEME.equals(key)) {
            ListSelectedRowCollection collection = getSelectedRows();
            if (collection.size() == 1) {
                DynamicObject entity = BusinessDataServiceHelper.loadSingle(collection.get(0).getPrimaryKeyValue(), SchemePatrolPigFaConstant.FORMBILLID);
                String enable = entity.getString("wens_enable");
                String status = entity.getString(SchemePatrolPigFaConstant.BILLSTATUS);
                if (!StringUtils.equals(enable,EnableEnum.ENABLE)) {
                    getView().showErrorNotification("非可用数据无法被更新");
                    evt.setCancel(true);
                    return;
                } else if (!BillStatusEnum.AUDIT.equals(status)) {
                    getView().showErrorNotification("单据状态不为已审核");
                    evt.setCancel(true);
                    return;
                }
//                String uid = entity.getString(OperationSchemeConstant.WENS_SCHEME_UID);
//                QFilter qFilter = new QFilter(OperationSchemeConstant.WENS_SCHEME_UID, QCP.equals, uid);
//                qFilter.and(new QFilter(BaseDataConst.F_STATUS, QCP.not_equals, BillStatusEnum.AUDIT));
//                DynamicObject[] dynamicObjects = BusinessDataServiceHelper.load(OperationSchemeConstant.FORMBILLID, BaseDataConst.F_ID, qFilter.toArray());
//                if (dynamicObjects.length > 0) {
//                    getView().showErrorNotification("已存在未经过审核的方案，无法再次更新");
//                    evt.setCancel(true);
//                    return;
//                }
            } else {
                getView().showErrorNotification("一次性只能勾选一条数据进行复制更新");
                evt.setCancel(true);
                return;
            }

        }
    }

    @Override
    public void itemClick(ItemClickEvent evt) {
        super.itemClick(evt);
        String key = evt.getItemKey();
        if (WENS_COPY_SCHEME.equals(key)) {
            ListSelectedRowCollection collection = getSelectedRows();
            Object copyId = collection.get(0).getPrimaryKeyValue();
            BaseShowParameter showParameter = new BaseShowParameter();
            showParameter.getOpenStyle().setShowType(ShowType.MainNewTabPage);
            showParameter.setFormId(SchemePatrolPigFaConstant.FORMBILLID);
            showParameter.setStatus(OperationStatus.ADDNEW);
            showParameter.setCustomParam(BaseDataConst.F_ID, copyId);
            showParameter.setCloseCallBack(new CloseCallBack(this, SchemePatrolPigFaConstant.FORMBILLID));
            this.getView().showForm(showParameter);
        }
    }

    @Override
    public void filterContainerBeforeF7Select(BeforeFilterF7SelectEvent args) {
        ListShowParameter parameter = (ListShowParameter) this.getView().getFormShowParameter();
        if (parameter.isLookUp()) {
            return;
        }
        // 猪场字段
        String pigGeryFieldName = this.getPageCache().get(ORG_FIELD);
        if (args.getRefEntityId().equals(pigGeryFieldName) || "bos_org".equals(args.getRefEntityId())) {
            args.addCustomQFilter(new QFilter(F_ID, QCP.in, PigGeryUtil.getPermPigGeryOrgList()));
        }
    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);
        FormOperate operate = (FormOperate) args.getSource();
        String operateKey = operate.getOperateKey();
        ListSelectedRowCollection collection = getSelectedRows();
        //没有v1.0的数据;
        boolean flag = false;
        if(org.apache.commons.lang3.StringUtils.equals(operateKey,"audit")){
            if(collection.size() != 1 ){
                this.getView().showTipNotification("方案审核时,请一次性只勾选一条数据进行!");
            }
            String checkaudit = this.getView().getPageCache().get("checkauditid");
            for(ListSelectedRow objRow: collection){
                DynamicObject object = BusinessDataServiceHelper.loadSingle(objRow.getPrimaryKeyValue(), SchemePatrolPigFaConstant.FORMBILLID);
                if(StringUtils.equals(object.getString(SchemePatrolPigFaConstant.WENS_VERSIONNUM),VERSIONNUM)
                        && !StringUtils.equals(object.getString(SchemePatrolPigFaConstant.BILLSTATUS),BillStatusEnum.AUDIT)){
                    if(ObjectUtil.isNull(checkaudit)) {
                        this.getView().getPageCache().put("checkauditid", object.getPkValue().toString());
                        flag = true;
                    }
                }
            }
            if(flag){
                ConfirmCallBackListener confirmCallBacks = new ConfirmCallBackListener("billaudit", this);
                this.getView().showConfirm("是否立刻生成巡查计划?", MessageBoxOptions.YesNo,
                        ConfirmTypes.Wait, confirmCallBacks);
                args.setCancel(true);
            }
        }
    }

    @Override
    public void confirmCallBack(MessageBoxClosedEvent messageBoxClosedEvent) {
        super.confirmCallBack(messageBoxClosedEvent);
        try {
            String callbackid = messageBoxClosedEvent.getCallBackId();
            if (StringUtils.equals("billaudit", callbackid)){
                String checkauditid = this.getView().getPageCache().get("checkauditid");
                if(QueryServiceHelper.exists(SchemePatrolPigFaConstant.FORMBILLID, checkauditid)){
                    DynamicObject obj = BusinessDataServiceHelper.loadSingle(checkauditid, SchemePatrolPigFaConstant.FORMBILLID);
                    if(messageBoxClosedEvent.getResult() == MessageBoxResult.Yes){
                        obj.set(SchemePatrolPigFaConstant.WENS_INADVANCE,true);
                        SaveServiceHelper.update(obj);
                        this.getView().invokeOperation("audit");
                    }else if(messageBoxClosedEvent.getResult() == MessageBoxResult.No){
                        obj.set(SchemePatrolPigFaConstant.WENS_INADVANCE,false);
                        SaveServiceHelper.update(obj);
                        this.getView().invokeOperation("audit");
                    }
                }
                this.getView().getPageCache().remove("checkauditid");
            }
        }catch (Exception e){
            this.getView().getPageCache().remove("checkauditid");
        }
    }
}
